import 'dart:convert';
import 'dart:js';
import 'package:flutter/material.dart';
import 'package:translation/entity/auth_entity.dart';
import 'package:translation/entity/js_data_entity.dart';
import 'package:translation/net/HttpManager.dart';
import 'package:translation/net/NetApi.dart';

import 'entity/to_js_model.dart';
import 'net/DataHelper.dart';
import 'net/ResultData.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Translation',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Translation'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  var _token = "";

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  void initState() {
    _authRequest(); //开始网络请求

    super.initState();
  }

  /// 调用js
  void _callJS(String data) {
    print("日志" + data);

    // context.callMethod("alert", [data]);
  }

  /// 调用js
  void _jsCallFlutter() {
//    等于js调用：flutter.flutterMoth();
    context.callMethod("flutterMethod", [""]);
  }

  /// 调用js并且传递参数
  void _callJSAndParameter() {
    //等于js调用： alert("我是来自dart的方法");
    context.callMethod("alert", ["我是来自dart的方法"]);
  }

  /// 调用js传参数返回数据
  void _callJSAndParameterAndReturn() {
    //等于js调用：var a = Math.pow(3,4);
    var callMethod = context["Math"].callMethod("pow", [3, 4]);
    context.callMethod("alert", [callMethod.toString()]);
    print("普通调用" + callMethod.toString());
  }

/*这里需要webView注册
   *JavascriptInterface 名为Obtain，并提供getA方法
   * 详细使用请百度android与js交互
   */
  void getNativeProperty() {
    //等于js调用：Obtain。getA()
    var text = context["obtain"].callMethod("getProperty", ["账号信息"]);
    context.callMethod("alert", [text.toString()]);
  }

  /// 调用日志，这里其实不必用这个了，因为fltter print，就等价于这个
  void jsConsoleLog() {
    //等于调用js：  console.log("我是dart 打印的js日志")
    context['console'].callMethod("log", ["我是dart 打印的js日志"]);
  }

  /// flutter方法用于让js调用
  void flutterMethod(dynamic jsData) {
    var data = json.decode(jsData);
    var jsDataEntity = JsDataEntity.fromJson(data);
    _translateRequest(jsDataEntity);

  }

  /// 网络请求
  void _authRequest() async {
    var params = DataHelper.getBaseMap();
    params.clear();
    params["action"] = "getAccessTokenByApp";
    // params["appid"] = "ab011be7-570f-4178-b9bc-2f0a7f2b2fe8";
    params["appid"] = "35dcdf47-247c-42dc-b07d-635faf9afb73";
    // params["appsecret"] = "a925117f";
    params["appsecret"] = "9b6fe1bc";
    ResultData res = await HttpManager.getInstance().get(NetApi.AUTH, params: params);
    var authEntity = AuthEntity.fromJson(res.data);
    _token = authEntity.accessToken![0].toString();

    setState(() {
      // ///正确的方式是
      //  if(res.isSuccess){
      //  }else{
      //  }

      // FilmEntity entity = FilmEntity.fromJson(res.data);
      // _films = entity.subjects;
    });
  }

  /// 开始翻译请求
  /// flutterMethod参数改成对象，{type:'receive',text:'原文文字'}（接收到的信息）
  /// ，{type:'send',text:'原文文字'}（要发送的信息）。receive类型的你翻译完调用我这边的receivefn函数
  /// ，send类型的要调用sendfn函数
  /// receive代表客户发送文字 , language 代表目标语言 如果是send的话就代表源语言
  void _translateRequest(JsDataEntity entity) async {
    var params = DataHelper.getBaseMap();
    params.clear();
    params["type"] = "text";
    params["srclang"] = entity.type == "receive" ? entity.language : "zh-cn";
    params["tgtlang"] = entity.type == "receive" ? "zh-cn" : entity.language;
    params["src"] = entity.text.toString();
    params["domain"] = "general";
    params["accesstoken"] = _token;
    ResultData res = await HttpManager.getInstance().get(NetApi.TRANSLATE, params: params);
    var json = new ToJsModel(res.data, entity.text);
    // print("高级调用js调用flutter" + jsonEncode(json));
    if (entity.type == "receive") {
      context.callMethod("receivefn", [jsonEncode(json)]);
      // context.callMethod("receivefn", ['{"data":"${res.data}","text":"${entity.text}"}']);
    } else {
      context.callMethod("sendfn", [json.data]);
    }

  }

  @override
  Widget build(BuildContext mContext) {
    context["flutterMethod"] = flutterMethod;
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RaisedButton(
              child: Text(
                '呼叫js',
              ),
              onPressed: _callJSAndParameter,
            ),
            RaisedButton(
                child: Text(
                  '呼叫js并传参数',
                ),
                onPressed: _callJSAndParameter),
            RaisedButton(
                child: Text(
                  '呼叫js传参数并返回数据',
                ),
                onPressed: _callJSAndParameterAndReturn),
            RaisedButton(
                child: Text(
                  'js打印日志',
                ),
                onPressed: jsConsoleLog),
            RaisedButton(
                child: Text(
                  'js 呼叫Flutter',
                ),
                onPressed: _jsCallFlutter),
            RaisedButton(
                child: Text(
                  '获取原生数据（需要客户端支持）',
                ),
                onPressed: getNativeProperty),
            RaisedButton(
                child: Text(
                  '用Dio网络请求Api',
                ),
                onPressed: getNativeProperty)
          ],
        ),
      ),
    );
  }
}
